﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebUI.Services
{
    using DocumentFormat.OpenXml;
    using DocumentFormat.OpenXml.Spreadsheet;
    using DocumentFormat.OpenXml.Packaging;
    public class DocumentServices
    {

        public static byte[] CreateSpreadsheetDocument(string sheetTitle,string[] titles,IList<string[]> data)//, params Func<string>[] values)//System.IO.Stream streamx)
        {
            //if (titles.Length != data.Count) throw new ArgumentException("列数与取值表达式数不匹配");

            using (var stream = new System.IO.MemoryStream())
            {
                using (var xlDoc = SpreadsheetDocument.Create(stream, SpreadsheetDocumentType.Workbook))
                {

                    WorkbookPart bookPart = xlDoc.AddWorkbookPart();
                    Workbook book = new Workbook();
                    bookPart.Workbook = book;

                    WorksheetPart sheetPart = bookPart.AddNewPart<WorksheetPart>();
                    SheetData sd = new SheetData();
                    Worksheet worksheet = new Worksheet(sd);
                    sheetPart.Worksheet = worksheet;

                    Sheets sheets = new Sheets();
                    book.AppendChild<Sheets>(sheets);

                    Sheet sheet = new Sheet() { Id = bookPart.GetIdOfPart(sheetPart), SheetId = 1001, Name = sheetTitle };
                    sheets.Append(sheet);

                    var titlecells = new Cell[titles.Length];
                    for (int i = 0; i < titles.Length; i++)
                    {
                        titlecells[i] = new Cell()
                        {
                            CellValue = new CellValue(titles[i]),
                            DataType = new EnumValue<CellValues>(CellValues.String)
                        };
                    }
                    sd.Append(new Row(titlecells));


                    var rs = new Row[data.Count];
                    var dt = new EnumValue<CellValues>(CellValues.String);
                    for (int r = 0; r < rs.Length; r++)
                    {

                        var cs = new Cell[data[r].Length];
                        for (int c = 0; c < cs.Length; c++)
                        {
                            cs[c] = new Cell()
                            {
                                CellValue = new CellValue(data[r][c]),
                                DataType = dt
                            };
                        }
                        rs[r] = new Row(cs);
                    }

                    sd.Append(rs);
                }
                return stream.ToArray();
            }
        }

    }
}